//
//  UserViewController.m
//  xpkc
//
//  Created by wanmeizty on 14-8-18.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "UserViewController.h"

@interface UserViewController ()
{
    UITableView *_tableView;
//    UILabel *_label;
    UIButton *_login;
    UIView *_foot_View;
    MyNotificationViewController *_myNotiVc;
    NSMutableArray *_msgArray;
    BOOL msgIsNil;
    UIButton *_msgBtn;
    CLLocationManager *locationManager;
}
@end

@implementation UserViewController{
    UISwitch *remindSwitch;
    UISwitch *wifiSwitch;
    UISwitch *rememeberSwitch;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        msgIsNil=0;
        // Custom initialization
        self.navigationItem.title = @"设置";
        
        self.tabBarItem.image = [UIImage imageNamed:@"tab_my"];
        if (IsIOS7) {
            self.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_my_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationController.navigationBar.hidden = NO;
    
    if (IsIOS7) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    //FIXME:定位，暂时放着
    logdebug(@"定位");
    if ([CLLocationManager locationServicesEnabled]) {
        locationManager = [[CLLocationManager alloc]init];
        locationManager.delegate = self;
    }
    [locationManager startUpdatingLocation];
    
    [self drawTableView];
    
}


//用户名显示
- (void)viewWillAppear:(BOOL)animated{
//    self.navigationController.navigationBar.hidden = NO;
    
    
    if ( ![UserMessage sharedUserMessage].isLogin ) {
        [_login setTitle:@"请登录" forState:UIControlStateNormal];
    }else{
        [_login setTitle:[UserMessage sharedUserMessage].userId forState:UIControlStateNormal];
    }
    if ([_login.titleLabel.text isEqualToString:@"请登录"]) {
        _foot_View.hidden=YES;
        [_login setUserInteractionEnabled:YES];
    }else{
        _foot_View.hidden=NO;
        [_login setUserInteractionEnabled:NO];
    }
    _login.titleLabel.font = FONT_SYS_NORMAL;
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(numChange) name:@"numChange" object:nil];
}
//
-(void)numChange{
    logdebug(@"%ld",_myNotiVc.numChange11);
    if (_myNotiVc.numChange11==0) {
        self.tabBarItem.badgeValue=nil;
        _msgBtn.hidden=YES;
        self.tabBarItem.image = [UIImage imageNamed:@"set"];
        if (IsIOS7) {
            self.tabBarItem.selectedImage = [[UIImage imageNamed:@"set_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }
    }else{
        if (IsIOS7) {
            self.tabBarItem.image = [[UIImage imageNamed:@"set1"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            self.tabBarItem.selectedImage = [[UIImage imageNamed:@"set1_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }else{
            self.tabBarItem.badgeValue=@"";
        }
        [_msgBtn setTitle:[NSString stringWithFormat:@"%ld",(long)_myNotiVc.numChange11] forState:UIControlStateNormal];
        
    }
}
//创建视图
-(void)drawTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 10, Window_Width, self.view.bounds.size.height-100) style:UITableViewStyleGrouped];
//    _tableView.contentSize=CGSizeMake(Window_Width, self.view.frame.size.height+110);
    CGRect head_frame;
    
    if (isPad) {
        head_frame = RECT(0, 0, 100, 100);
    }else{
        head_frame = RECT(0, 0, 100, 90);
    }

    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.backgroundColor=RGBCOLOR(231, 236, 237);
    [self.view addSubview:_tableView];
    
}
-(void)backlogin{
    self.tabBarController.selectedIndex = 2;
}


#pragma mark - =======tableView delegate & dataSource========
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (isPad) {
        return 60;
    }
    return 44;
}
//section之间的间隔
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1; // you can have your own choice, of course
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 4;
    } else if (section == 1) {
        return 2;
    }
    return 2;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
/**
 *   创建我的设置视图
 *
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = FONT_SYS_NORMAL;
        cell.detailTextLabel.textColor = [UIColor lightGrayColor];
        switch (section) {
            case 0:
                if(row == 0)
                {
                    cell.accessoryType=UITableViewCellAccessoryNone;
                    cell.textLabel.text =  @"学习提醒";
                    cell.detailTextLabel.text = @"根据学习进度定期进行学习提醒";
                    CGRect switch_frame;
                    if (IsIOS7) {
                        switch_frame = RECT(SCREEN_WIDTH-70, 7, 40, cell.frame.size.height);
                    }else{
                        switch_frame = RECT(SCREEN_WIDTH-90, 7, 40, cell.frame.size.height);
                    }
                    remindSwitch = [[UISwitch alloc] initWithFrame:switch_frame];
                    NSString *yesorno = [[NSUserDefaults standardUserDefaults] valueForKey:REMIND_STUDY];
                    if([yesorno isEqualToString:@"NO"]) {
                        remindSwitch.on = NO;
                    } else {
                        remindSwitch.on = YES; // 进行定期学习提醒
                    }
                    [self setREMIND_ONLYinfo];
                    [remindSwitch addTarget:self action:@selector(changeREMIND_Switch) forControlEvents:UIControlEventValueChanged];
                    [cell addSubview:remindSwitch];

                }else if(row == 1){
                    cell.accessoryType=UITableViewCellAccessoryNone;
                    cell.textLabel.text =  @"仅在WiFi下观看和下载";
                    CGRect switch_frame;
                    if (IsIOS7) {
                        switch_frame = RECT(SCREEN_WIDTH-70, 7, 40, cell.frame.size.height);
                    }else{
                        switch_frame = RECT(SCREEN_WIDTH-90, 7, 40, cell.frame.size.height);
                    }
                    wifiSwitch = [[UISwitch alloc]initWithFrame:switch_frame];
                    NSString * yesorno = [[NSUserDefaults standardUserDefaults]valueForKey:WIFI_ONLY];
                    if ([yesorno isEqualToString:@"NO"]) {
                        wifiSwitch.on = NO;
                    }else{
                        wifiSwitch.on = YES;//默认只在wifi下才能下载
                    }
                    //初始的时候就保存一下
                    [self setWIFI_ONLYinfo];
                    [wifiSwitch addTarget:self action:@selector(changeWIFI_ONLYswitch) forControlEvents:UIControlEventValueChanged];
//                    wifiSwitch.tintColor = [UIColor orangeColor];
                    [cell addSubview:wifiSwitch];
                }else if(row == 2){
                    cell.accessoryType=UITableViewCellAccessoryNone;
                    cell.textLabel.text = @"是否跳转上次播放位置";
                    CGRect remember_frame;
                    if (IsIOS7) {
                        remember_frame = RECT(SCREEN_WIDTH-70, 7, 40, cell.frame.size.height);
                    }else{
                        remember_frame = RECT(SCREEN_WIDTH-90, 7, 40, cell.frame.size.height);
                    }
                    rememeberSwitch = [[UISwitch alloc]initWithFrame:remember_frame];
                    NSString * yesorno = [[NSUserDefaults standardUserDefaults]valueForKey:REMEMBER_LAST];
                    if ([yesorno isEqualToString:@"NO"]) {
                        rememeberSwitch.on = NO;
                    }else{
                        rememeberSwitch.on = YES;//默认继续播放
                    }
                    [self setREMEMBER_ONLYinfo];
                    [rememeberSwitch addTarget:self action:@selector(changeREMEMBER_LASTswitch) forControlEvents:UIControlEventValueChanged];
                    [cell addSubview:rememeberSwitch];
                }else{
                    
                    cell.accessoryType=UITableViewCellAccessoryNone;
                    cell.textLabel.text =  [NSString stringWithFormat:@"清除文件缓存（%0.1fM）",[GetFileSize folderSizeAtPath:DOC_PATH]];
                    cell.detailTextLabel.text = @"清理本地下载的全部视频缓存";
                    cell.selectionStyle = UITableViewCellSelectionStyleGray;

                }
                break;
            case 1:
                if(row == 0){
                    cell.textLabel.text =  @"去评分";
                }else{
                    cell.textLabel.text =  @"意见反馈";
                }
                break;
            case 2:
                if (row == 0) {
                    cell.textLabel.text = @"功能介绍";
                } else {
                    cell.textLabel.text = @"关于";
                }
                break;
            default:
                break;
        }
    }
    return cell;
}
/**
 *   点击不同行，跳转不同
 *
 */
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell =  [_tableView cellForRowAtIndexPath:indexPath];
    cell.selected = NO;
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                {
                    // 改变是否定期提醒学习
                    [self changeREMIND_ONLYiswitch];

                }
                    break;
                case 1:
                {
                    //改变wifi信息
                    [self changeWIFI_ONLY];
                }
                    break;
                case 2:
                {
                    //改变是否记录上次播放
                    [self changeREMEMBER_LAST];
                }
                    break;
                case 3:
                {
                    //清除缓存通知
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"确认要删除本地缓存文件吗" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    alert.tag = 100;
                    [alert show];
                }
                    break;
                    
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            switch (indexPath.row) {
                case 0:
                {
                    NSString *str2 = [NSString stringWithFormat: @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=%@",  @"897012923"];
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str2]];
                }
                    break;
                case 1:
                {
                    FeedbackViewController *vc=[[FeedbackViewController alloc]init];
                    [self.navigationController pushViewController:vc animated:YES];
                    if (IsIOS7) {
                        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
                            self.navigationController.interactivePopGestureRecognizer.delegate = nil;
                        }
                    }
                }
                    break;
                default:
                    break;
            }
            
        }
            break;
        case 2:
        {
            switch (indexPath.row) {
                case 0:
                {
                    logdebug(@"功能介绍!!!");
                    logdebug(@"再跑一遍引导页");
                }
                    break;
                case 1:
                {
                    AboutViewController *vc=[[AboutViewController alloc]init];
                    [self.navigationController pushViewController:vc animated:YES];
                    if (IsIOS7) {
                        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
                            self.navigationController.interactivePopGestureRecognizer.delegate = nil;
                        }
                    }
                }
                    break;
                    
                default:
                    break;
            }
        }
            
        default:
            break;
    }
}
//前往appstore更新
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==889){
        self.tabBarController.selectedIndex=2;
    }
    if (alertView.tag==10000) {
        if (buttonIndex==1) {
            NSURL *url = [NSURL URLWithString:self.updateNewURL];
            [[UIApplication sharedApplication]openURL:url];
        }
    }
    if (alertView.tag == 100) {
        //确定
        //删除本地数据
        if (buttonIndex == 1) {
            //发送通知
            [[NSNotificationCenter defaultCenter]postNotificationName:CLEAR_DATA_REFRESH_TABLEVIEW object:nil];
            UITableViewCell *cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:3 inSection:0]];
            cell.textLabel.text =  [NSString stringWithFormat:@"清除离线视频（0.0M）"];
        }
    }
}
//改变只在WiFi下下载的选项(cell的方法)
-(void)changeWIFI_ONLY{
    //如果只在wifi下的话就改变，并且将信息添加到本地的userdefault中
    if (wifiSwitch.on) {
        //
        [wifiSwitch setOn:NO animated:YES];
        logdebug(@"随便下");
        [self setWIFI_ONLYinfo];
    }else{
        [wifiSwitch setOn:YES animated:YES];
        //变成必须wifi
        logdebug(@"现在必须wifi下才行");
        [self setWIFI_ONLYinfo];
    }
}
//改变只在WiFi下下载的选项(switch的方法)
-(void)changeWIFI_ONLYswitch{
    if (!wifiSwitch.on) {
        //
        [wifiSwitch setOn:NO animated:YES];
        logdebug(@"随便下");
        [self setWIFI_ONLYinfo];
    }else{
        [wifiSwitch setOn:YES animated:YES];
        //变成必须wifi
        logdebug(@"现在必须wifi下才行");
        [self setWIFI_ONLYinfo];
    }
}
//改变只在WiFi下下载的选项(cell的方法)
-(void)changeREMEMBER_LAST{
    //如果只在wifi下的话就改变，并且将信息添加到本地的userdefault中
    if (rememeberSwitch.on) {
        //
        [rememeberSwitch setOn:NO animated:YES];
        logdebug(@"随便下");
        [self setREMEMBER_ONLYinfo];
    }else{
        [rememeberSwitch setOn:YES animated:YES];
        //变成必须wifi
        logdebug(@"现在必须wifi下才行");
        [self setREMEMBER_ONLYinfo];
    }
}
//改变是否跳转到播放位置
-(void)changeREMEMBER_LASTswitch{
    if (!rememeberSwitch.on) {
        //从头开始播放
        [rememeberSwitch setOn:NO animated:YES];
        logdebug(@"从头开始播放");
        [self setREMEMBER_ONLYinfo];
    }else{
        [rememeberSwitch setOn:YES animated:YES];
        //继续上次播放
        logdebug(@"继续上次播放");
        [self setREMEMBER_ONLYinfo];
    }

}
// 改变是否定期提醒学习
- (void)changeREMIND_Switch {
    if(!remindSwitch.on) {
        // 不进行学习提醒
        [remindSwitch setOn:NO animated:YES];
        [self setREMIND_ONLYinfo];
    } else {
        [remindSwitch setOn:YES animated:YES];
        [self setREMIND_ONLYinfo];
    }
}
// 改变是否定期提醒学习 (cell 方法)
- (void)changeREMIND_ONLYiswitch {
    if(remindSwitch.on) {
        // 不进行学习提醒
        [remindSwitch setOn:NO animated:YES];
        [self setREMIND_ONLYinfo];
    } else {
        [remindSwitch setOn:YES animated:YES];
        [self setREMIND_ONLYinfo];
    }
}
//将只在wifi下进行保存?本地化好呢还是暂存好呢
//本地化
-(void)setWIFI_ONLYinfo{
    [[NSUserDefaults standardUserDefaults]setValue:wifiSwitch.on == YES?@"YES":@"NO" forKey:WIFI_ONLY];
    [[NSUserDefaults standardUserDefaults]synchronize];
}
//是否记住上次播放位置
-(void)setREMEMBER_ONLYinfo{
    [[NSUserDefaults standardUserDefaults]setValue:rememeberSwitch.on == YES?@"YES":@"NO" forKey:REMEMBER_LAST];
    [[NSUserDefaults standardUserDefaults]synchronize];
}
// 是否进行定期学习提醒
- (void)setREMIND_ONLYinfo {
    [[NSUserDefaults standardUserDefaults] setValue:remindSwitch.on == YES ? @"YES":@"NO" forKey:REMIND_STUDY];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
